package com.itheima.clientAndService02;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class RunnableClass implements Runnable {

    private Socket accept;

    public RunnableClass(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        BufferedWriter bw = null;
        try {
            //创建字节缓冲输入流，从网络上接收客户端发送过来的数据
            bis = new BufferedInputStream(accept.getInputStream());
            String filename = UUID.randomUUID().toString().replace("-","") + ".jpg";
            //创建字节缓冲输出流，保存上传的文件
            bos = new BufferedOutputStream(new FileOutputStream("day17_practice\\aaa\\" + filename));
            //保存发送过来的数据
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }

            //创建字符缓冲输出流对象，向客户端反馈数据上传信息
            bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            //写反馈
            String line = "上传成功！";
            bw.write(line);
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null) {
                     accept.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
